//
//  XHQHttpTool.m
//  XiongMaoJiaSu
//
//  Created by 徐汉卿 on 16/5/30.
//  Copyright © 2016年 ISOYasser. All rights reserved.
//

#import "XHQHttpTool.h"





@implementation XHQHttpTool

+(NSString *)xhqpostWL:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSString *urlStr,NSDictionary *json))success failure:(void (^)(NSString *urlStr,NSError *error))failure timeOut:(NSInteger)timeOut showMB:(BOOL)showMB toView:(UIView *)view{
    
    
    XHQWeak(view, weakViw);
//    if (![url hasPrefix:@"/"]) {
//        url = [@"/" stringByAppendingString:url];
//    }
    if ([url hasPrefix:@"/"]) {
          url = [url substringFromIndex:1];
    }
    
//    NSMutableDictionary *params2 = [NSMutableDictionary dictionary];
    if (params ==nil) {
        params = [NSMutableDictionary dictionary];
    }
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] valueForKey:@""];
    
    if (accessToken) {
        
        [params setValue:accessToken forKey:@"access_token"];
        
    }
    
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    appVersion = [appVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
    
    [params setValue:@"1" forKey:@"platform"];
    //    [NSNumber numberWithInt:213];//appVersion
    [params setValue:appVersion forKey:@"version"];
    
    return  [self xhqpost: [@"baseURL" stringByAppendingString:url] params:params success:^(NSString *urlStr, NSDictionary *json) {
        if (success) {
            
            if ([json[@"status"] intValue]==0) {
                success(urlStr,json[@"data"]);
                
            }else{
                [json[@"message"] showHUD:1];
            }
//            success(urlStr,json);
        }
        
        
    } failure:^(NSString *urlStr, NSError *error) {
        NSLog(@"-xhqxhq--%ld",(long)error.code);
        if (failure) {
            
            
            if (showMB) {
              
//                  [error.localizedDescription showHUD:1];
                
              
                
                if (error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]) {
                    //服务器有返回数据
                    NSDictionary *response = [NSJSONSerialization JSONObjectWithData:error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
                     [response[@"message"] showHUD:1];
                }else{
                      [error.localizedDescription showHUD:1];
                }
//
                
            }
            
            // 错误码
//            response[@"status"];
            // 错误消息
//            response[@"message"]
            
            if (error.code == 401) {
                //提示用户重新登录
                  [[NSNotificationCenter defaultCenter] postNotificationName:WL_ACCESS_TOKEN_INVALID_NOTI object:nil];
                return ;
            }
//
            failure(urlStr,error);
        }
        
    } timeOut:outline showMB:showMB toView:weakViw];
}

//未加密的数据解析
+(NSString *)xhqpost:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSString *urlStr,NSDictionary *json))success failure:(void (^)(NSString *urlStr,NSError *error))failure timeOut:(NSInteger)timeOut showMB:(BOOL)showMB toView:(UIView *)view
{
    
    
    
    NSArray *keyArray = [params allKeys];
    NSString *str = url;
    if (params) {
        
        str = [NSString stringWithFormat:@"%@?",url];
        for (int i= 0; i <keyArray.count; i++) {
            NSString *key =keyArray[i];
            NSString *value = [params objectForKey:keyArray[i]];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,value]];
        }
        str =[str substringToIndex:str.length-1];
    }
    
  
    
    // 1.创建请求管理者
 AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    AFHTTPRequestSerializer *requestSerializer=[[AFHTTPRequestSerializer alloc] init];
    
        [requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
        mgr.requestSerializer=requestSerializer;
    
    
//     mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];
    
    //之前代码
//     AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//    AFHTTPResponseSerializer *jsonSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];
//    NSArray *accptTypes = [NSArray arrayWithObjects:@"text/plain",@"text/html", nil];
//    jsonSerializer.acceptableContentTypes = [jsonSerializer.acceptableContentTypes setByAddingObjectsFromArray:accptTypes];
//
//
//    mgr.responseSerializer = jsonSerializer;
    
    
    
//    AFHTTPRequestSerializer *requestSerializer=[[AFHTTPRequestSerializer alloc] init];
//    requestSerializer.timeoutInterval = 30.f;//30秒超时设定
//    requestSerializer.cachePolicy=NSURLRequestReloadRevalidatingCacheData;
//    //            requestSerializer.cachePolicy=NSURLRequestUseProtocolCachePolicy;
//    NSString *version = [@"3.1.2" stringByReplacingOccurrencesOfString:@"." withString:@""];
//
//    [requestSerializer setValue:@"1" forHTTPHeaderField:@"platform"];
//    [requestSerializer setValue:version forHTTPHeaderField:@"version"];
//
//
//    [requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//
//    mgr.requestSerializer=requestSerializer;
//
    
    
    
    
    if (timeOut)
    {
        mgr.requestSerializer.timeoutInterval = timeOut;
        
    }else{
        
        mgr.requestSerializer.timeoutInterval = 10.f;
    }

     MBProgressHUD *thisHUD  = nil;
    if (showMB)
    {
        if (view ==nil)
        {
            view = [UIApplication sharedApplication].keyWindow;
        }
        thisHUD = [MBProgressHUD  showHUDAddedTo:view animated:YES];
        
        
    }
    [mgr POST:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            [thisHUD hide:NO];
            //NSJSONReadingAllowFragments    //NSJSONReadingMutableContainers
            NSError *error;
            NSDictionary *dicR = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
              NSLog(@"网址%@",str);
            XHQLog(@"返回的字典%@",dicR);
               NSLog(@"-----------xhqcuowu------%@",error);
            success(str,dicR);
            
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [thisHUD hide:NO];
        if (failure) {
            failure(str,error);
        }
    }];

  
    
    return str;
    
}



/**
 *  加密的数据解析
 *
 *
 *
 *  @return <#return value description#>
 */
//+(NSString *)xhqpost:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSString *urlStr,NSDictionary *json))success failure:(void (^)(NSString *urlStr,NSError *error))failure timeOut:(NSInteger)timeOut showMB:(BOOL)showMB toView:(UIView *)view
//{
//    
//    
//    
//    NSArray *keyArray = [params allKeys];
//    NSString *str = url;
//    if (params) {
//        
//        str = [NSString stringWithFormat:@"%@?",url];
//        for (int i= 0; i <keyArray.count; i++) {
//            NSString *key =keyArray[i];
//            NSString *value = [params objectForKey:keyArray[i]];
//            str = [str stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,value]];
//        }
//        str =[str substringToIndex:str.length-1];
//    }
//    
//     NSLog(@"网址%@",str);
//    // 1.创建请求管理者
//    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//    
//    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
//    if (timeOut)
//    {
//        mgr.requestSerializer.timeoutInterval = timeOut;
//        
//    }else{
//        
//        mgr.requestSerializer.timeoutInterval = 10.f;
//    }
//    
//    
//    
//    
//    if (showMB)
//    {
//        //        [UIApplication sharedApplication].keyWindow
//        [LCProgressHUD showLoading:nil];
//        
//        
//    }
//    [mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        [LCProgressHUD hide];
//        if (success) {
//            NSString *key = @"4cb4e74033fa753935c873e664323486@";
//            NSString *str1=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//            
//            NSString *strTemp = [cccc XorDencodeWithKey:key str:str1];
//
//            NSData* xmlData = [strTemp dataUsingEncoding:NSUTF8StringEncoding];
//            
//            
//            NSDictionary *dicRESULT = [NSJSONSerialization JSONObjectWithData:xmlData options:NSJSONReadingMutableContainers error:nil];
//            XHQLog(@"返回的字典%@",dicRESULT);
//            success(str,dicRESULT);
//        }
//        //        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:[responseObject valueForKey:@"msg"] message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        //        [alert show];
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        [LCProgressHUD hide];
//        if (failure) {
//            failure(str,error);
//        }
//        //        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"加载失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        //        [alert show];
//    }];
//    
//    
//    return str;
//    
//}




+(NSString *)xhqReTryPost:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSString *urlStr,id json))success failure:(void (^)(NSString *urlStr,NSError *error))failure timeOut:(NSInteger)timeOut showMB:(BOOL)showMB toView:(UIView *)view{
    return  [self xhqpost:url params:params success:success failure:^(NSString *urlStr, NSError *error) {
         [self xhqReTryPost:url params:params success:success failure:failure timeOut:timeOut showMB:showMB toView:view];
    } timeOut:timeOut showMB:showMB toView:view];
}






//---get

+(NSString *)xhq_GET:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSString *urlStr,NSDictionary *json))success failure:(void (^)(NSString *urlStr,NSError *error))failure timeOut:(NSInteger)timeOut showMB:(BOOL)showMB toView:(UIView *)view
{
    
    
    
    NSArray *keyArray = [params allKeys];
    NSString *str = url;
    if (params) {
        
        str = [NSString stringWithFormat:@"%@?",url];
        for (int i= 0; i <keyArray.count; i++) {
            NSString *key =keyArray[i];
            NSString *value = [params objectForKey:keyArray[i]];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,value]];
        }
        str =[str substringToIndex:str.length-1];
    }
    
    NSLog(@"网址%@",str);
    
    // 1.创建请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (timeOut)
    {
        mgr.requestSerializer.timeoutInterval = timeOut;
        
    }else{
        
        mgr.requestSerializer.timeoutInterval = 10.f;
    }
    
    
    
    
    MBProgressHUD *thisHUD  = nil;
    
    if (showMB)
    {

        
        if (view ==nil)
        {
            view = [UIApplication sharedApplication].keyWindow;
        }
         thisHUD = [MBProgressHUD  showHUDAddedTo:view animated:YES];
//                thisHUD = [[MBProgressHUD alloc] initWithView:view];
//                thisHUD.graceTime = 0.5;
//                [thisHUD show:YES];
        
        
    }
    [mgr GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"xxx  网络%@",[[UIApplication sharedApplication].windows lastObject]);
//        NSLog(@"xxx  字符串%@",[[UIApplication sharedApplication].windows lastObject]);
//        NSLog(@"xxx  %@",[[UIApplication sharedApplication].delegate window]);
        [thisHUD hide:NO];
        
        if (success) {
           
//            XHQLog(@"返回的data:%@",responseObject);
//            
//            NSString *jsonxx = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//            
//            
//            NSLog(@"请求地址%@\n\n  jsonxx:%@",str,jsonxx);
            XHQLog(@"返回的字典%@",[NSJSONSerialization JSONObjectWithData:responseObject options:2 error:nil]);
            success(str,[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      
        [thisHUD hide:NO];
        
        if (failure) {

            failure(str,error);
        }
    }];
    
    
    
    return str;
    
}



+(NSString *)xhqReTryGET:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSString *urlStr,id json))success failure:(void (^)(NSString *urlStr,NSError *error))failure timeOut:(NSInteger)timeOut showMB:(BOOL)showMB toView:(UIView *)view{
    return  [self xhq_GET:url params:params success:success failure:^(NSString *urlStr, NSError *error) {
        [self xhqReTryPost:url params:params success:success failure:failure timeOut:timeOut showMB:showMB toView:view];
    } timeOut:timeOut showMB:showMB toView:view];
}


@end
